package com.hongyi.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hongyi.common.framework.constant.Constants;
import com.hongyi.common.framework.constant.UserConstans;
import com.hongyi.common.framework.domain.JsonResult;
import com.hongyi.common.framework.utils.string.StringUtils;
import com.hongyi.common.framework.validate.AddGroup;
import com.hongyi.common.framework.validate.EditGroup;
import com.hongyi.common.log.annotation.Log;
import com.hongyi.common.log.enums.BusinessType;
import com.hongyi.common.web.controller.BaseController;
import com.hongyi.system.domain.RoleMenuTreeSelect;
import com.hongyi.common.saToken.utils.LoginUtils;
import com.hongyi.system.domain.SysMenu;
import com.hongyi.system.domain.TreeSelect;
import com.hongyi.system.domain.dto.SysMenuDto;
import com.hongyi.system.domain.vo.RouterVo;
import com.hongyi.system.domain.vo.SysMenuVo;
import com.hongyi.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 菜单信息
 *
 * @author DingHao
 */
@ApiSort(value = 4)
@Api( tags = "菜单信息接口")
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 获取菜单列表
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取菜单列表")
    @SaCheckPermission("system:menu:list")
    @GetMapping(value = "/list")
    public JsonResult<List<SysMenuVo>> list(SysMenu menu) {
        List<SysMenuVo> sysMenuVos = sysMenuService.selectMenuList(menu, LoginUtils.getUserId());
        return JsonResult.ok(sysMenuVos);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("/getRouters")
    public JsonResult<List<RouterVo>> getRouters() {
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(LoginUtils.getUserId());
        return JsonResult.ok(sysMenuService.buildMenus(menus));
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "获取菜单详细信息")
    @ApiImplicitParam(name = "menuId", value = "菜单ID", paramType = "path", dataTypeClass = Long.class, required = true)
    @SaCheckPermission("system:menu:query")
    @GetMapping(value = "/{menuId}")
    public JsonResult<SysMenuVo> getInfo(@PathVariable Long menuId) {
        return JsonResult.ok(sysMenuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "获取菜单下拉树列表")
    @GetMapping("/treeselect")
    public JsonResult<List<TreeSelect>> treeselect(SysMenu menu, HttpServletRequest request) {

        List<SysMenuVo> menus = sysMenuService.selectMenuList(menu, LoginUtils.getUserId());
        return JsonResult.ok(sysMenuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "加载对应角色菜单列表树")
    @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "path", dataTypeClass = Long.class, required = true)
    @GetMapping(value = "/roleMenuTreeSelect/{roleId}")
    public JsonResult<RoleMenuTreeSelect> roleMenuTreeSelect(@PathVariable("roleId") Long roleId) {
        List<SysMenuVo> menus = sysMenuService.selectMenuListById(LoginUtils.getUserId());
        RoleMenuTreeSelect treeSelect = new RoleMenuTreeSelect();
        treeSelect.setCheckedKeys(sysMenuService.selectMenuListByRoleId(roleId));
        treeSelect.setMenus(sysMenuService.buildMenuTreeSelect(menus));
        return JsonResult.ok(treeSelect);
    }

    /**
     * 新增菜单
     */
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增菜单")
    @SaCheckPermission("system:menu:add")
    @Log(title = "新增菜单", businessType = BusinessType.INSERT)
    @PostMapping
    public JsonResult<Void> add(@Validated(AddGroup.class) @RequestBody SysMenuDto sysMenuDto) {
        if (UserConstans.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(sysMenuDto))) {
            return JsonResult.fail("新增菜单'" + sysMenuDto.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstans.YES_FRAME.equals(sysMenuDto.getIsFrame())
                && !StringUtils.startsWithAny(sysMenuDto.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return JsonResult.fail("新增菜单'" + sysMenuDto.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        return toResult(sysMenuService.insertMenu(sysMenuDto));
    }

    /**
     * 修改菜单
     */
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "修改菜单")
    @SaCheckPermission("system:menu:edit")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public JsonResult<Void> edit(@Validated(EditGroup.class) @RequestBody SysMenuDto sysMenuDto) {
        if (UserConstans.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(sysMenuDto))) {
            return JsonResult.fail("修改菜单'" + sysMenuDto.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstans.YES_FRAME.equals(sysMenuDto.getIsFrame())
                && !StringUtils.startsWithAny(sysMenuDto.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return JsonResult.fail("修改菜单'" + sysMenuDto.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (sysMenuDto.getMenuId().equals(sysMenuDto.getParentId())) {
            return JsonResult.fail("修改菜单'" + sysMenuDto.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        return toResult(sysMenuService.updateMenu(sysMenuDto));
    }

    /**
     * 删除菜单
     */
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "删除菜单")
    @ApiImplicitParam(name = "menuId", value = "菜单ID", paramType = "path", dataTypeClass = Long.class, required = true)
    @SaCheckPermission("system:menu:remove")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public JsonResult<Void> remove(@PathVariable("menuId") Long menuId) {
        if (sysMenuService.hasChildByMenuId(menuId)) {
            return JsonResult.fail("存在子菜单,不允许删除");
        }
        if (sysMenuService.checkMenuExistRole(menuId)) {
            return JsonResult.fail("菜单已分配,不允许删除");
        }
        return toResult(sysMenuService.deleteMenuById(menuId));
    }

}
